package seg.tef4.whms.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.scan.R;

import org.json.JSONObject;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import seg.tef4.whms.apis.UserApi;
import seg.tef4.whms.domain.model.LoginBody;
import seg.tef4.whms.activity.activityinit.BaseActivity;
import seg.tef4.whms.util.auth.OnlineUser;
import seg.tef4.whms.util.dialog.AlertDialogCreator;
import seg.tef4.whms.util.nfc.NFCUtil;
import seg.tef4.whms.util.retrofitutil.RetrofitUtil;

import java.io.UnsupportedEncodingException;

public class LoginActivity extends BaseActivity {

    private NFCUtil nfcUtil;

    private EditText user_name_edit;
    private EditText password_edit;

    private Button button;

    private UserApi userApi = (UserApi) RetrofitUtil.getApiInstance(UserApi.class);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        user_name_edit = findViewById(R.id.login_user_editview);
        password_edit = findViewById(R.id.login_password_editview);
        button = findViewById(R.id.login_button);

        button.setOnClickListener(view -> {
            String user_name = user_name_edit.getText().toString();
            String password = password_edit.getText().toString();
            userLogin(user_name,password);
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        nfcUtil = new NFCUtil(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在onResume中开启前台调度
        nfcUtil.enableForegroundDispatch(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //关闭前台调度系统
        nfcUtil.disableForegroundDispatch(this);
    }

    /**
     * @description 读取到NFC设备时处理intent回调
     * @param intent
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        try {
            String id = nfcUtil.readNFCId(intent);
            userLoginNFC(id);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @description 用户登录
     * @param userName
     * @param password
     */
    private void userLogin(String userName,String password){
        LoginBody loginBody = new LoginBody();
        loginBody.setUsername(userName);
        loginBody.setPassword(password);
        loginBody.setCode("移动端无需验证码校验");

        userApi.userLogin(loginBody).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String resultJson = response.body().string();
                    JSONObject result = new JSONObject(resultJson);
                    int code = result.getInt("code");
                    String msg = result.getString("msg");
                    if(code == 200){
                        String token = result.getString("token");
                        OnlineUser.setToken(token);
                        IndexActivity.startIndexActivity(LoginActivity.this);
                        LoginActivity.this.finish();
                    }else{
                        String cmsg = new StringBuilder()
                                .append("错误码:\t").append(code).append("\n")
                                .append("消息:\t").append(msg)
                                .toString();
                        AlertDialog confirmDialog = AlertDialogCreator.getConfirmDialog(LoginActivity.this,
                                "登录失败",cmsg,"确认",null);
                        confirmDialog.show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    AlertDialog confirmDialog = AlertDialogCreator.getConfirmDialog(LoginActivity.this,
                            "系统错误",e.toString(),"确认",null);
                    confirmDialog.show();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                System.out.println(t.toString());
                AlertDialog confirmDialog = AlertDialogCreator.getConfirmDialog(LoginActivity.this,
                        "系统错误",t.toString(),"确认",null);
                confirmDialog.show();
            }
        });
    }

    private void userLoginNFC(String nfc){
        userApi.userLoginNFC(nfc).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String resultJson = response.body().string();
                    JSONObject result = new JSONObject(resultJson);
                    int code = result.getInt("code");
                    String msg = result.getString("msg");
                    if(code == 200){
                        String token = result.getString("token");
                        OnlineUser.setToken(token);
                        IndexActivity.startIndexActivity(LoginActivity.this);
                        LoginActivity.this.finish();
                    }else{
                        String cmsg = new StringBuilder()
                                .append("错误码:\t").append(code).append("\n")
                                .append("消息:\t").append(msg)
                                .toString();
                        AlertDialog confirmDialog = AlertDialogCreator.getConfirmDialog(LoginActivity.this,
                                "登录失败",cmsg,"确认",null);
                        confirmDialog.show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    AlertDialog confirmDialog = AlertDialogCreator.getConfirmDialog(LoginActivity.this,
                            "系统错误",e.toString(),"确认",null);
                    confirmDialog.show();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                System.out.println(t.toString());
                AlertDialog confirmDialog = AlertDialogCreator.getConfirmDialog(LoginActivity.this,
                        "系统错误",t.toString(),"确认",null);
                confirmDialog.show();
            }
        });
    }



}
